package com.malou.client.ventas.ingreso;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.RowNumberer;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.malou.client.MalouConstants;
import com.malou.client.util.Utilities;
import com.malou.client.ventas.serie.Series;

public class IngresoDialog extends Dialog {
	private Button guardar;
	private Button cancelar;
	public Status status;
	private MalouConstants constants = GWT.create(MalouConstants.class);
	
	public TextField<String> descripcion;
	public TextField<String> numerodocumento;
	public TextArea observacion;
	public ComboBox<BeanModel> documento;
	private NumberField monto;	
	private Button addDetalle;
	private Button delDetalle;
		
	private ListStore<BeanModel> store;
	private Grid<BeanModel> grid;
	private ToolBar toolBar;
	private FormPanel formpanel;
	private FieldSet gastoFieldSet;
	private ContentPanel gridPanel;
	
	public IngresoDialog(){
		super();
		setModal(true);
		setSize(700, 450);
		setResizable(false);	 
		setButtons("");
		setIconStyle("icon-stock");
		setHeading(constants.ingresoNuevo());
		
		formpanel = new FormPanel();
		formpanel.setBodyBorder(false);
		formpanel.setBodyBorder(false);
		formpanel.setHeaderVisible(false);
	    
		gastoFieldSet = new FieldSet();
		gastoFieldSet.setHeading(constants.ventaAgregarDetalle());
		gastoFieldSet.setStyleAttribute("padding", "8px");
		gastoFieldSet.setLayout(new ColumnLayout());
		
	    addFields();
	    setFocusWidget(descripcion);
	    Component comp[]={descripcion,monto,observacion,documento,numerodocumento,addDetalle};
	    Utilities.Enter(comp);
	    
	    
	}
	private void addFields() {
		
		toolBar = new ToolBar();
		toolBar.setBorders(false);
		
		descripcion = new TextField<String>();
		descripcion.setFieldLabel(constants.gastoDescripcion());
		
		monto = new NumberField();
		monto.setFieldLabel(constants.gastoImporte());		
		monto.setAllowNegative(false);
		monto.setPropertyEditorType(Double.class);
		
		
		Series.getComboDocumento();
	    Series.loaderCombo.load(); // for edit
	    
	    documento = new ComboBox<BeanModel>();  
	    documento.setEditable(false);
	    documento.setFieldLabel(constants.gastoDocumento());
	    
	    
	    documento.setDisplayField("descripcion");
	    documento.setEmptyText(constants.seleccione());	 	    
	    documento.setStore(Series.storeCombo);  
	    documento.setTypeAhead(true);  
	    documento.setTriggerAction(TriggerAction.ALL);
	    documento.setValueField("descripcion");
	    
	    documento.getStore().addStoreListener(new StoreListener<BeanModel>(){
	    	public void storeDataChanged(StoreEvent<BeanModel> se){
	    		super.storeDataChanged(se);
	    		List<BeanModel> list = new ArrayList<BeanModel>();
	    		list.add(documento.getStore().getAt(2));//documento: otro
	    		documento.setSelection(list);
	    	}
	    });
	  
		
		
		
		numerodocumento = new TextField<String>();
		numerodocumento.setFieldLabel(constants.gastoNumero());
		numerodocumento.addKeyListener(new KeyListener(){
			public void componentKeyDown(ComponentEvent event){
				if(event.getKeyCode() == KeyCodes.KEY_ENTER){										
					agregarDetalle();
					
				}
			}
		});
			
		
		observacion = new TextArea();
		observacion.setHeight(40);
		observacion.setFieldLabel(constants.gastoObservaciones());
		
		
		
		addDetalle = new Button(constants.agregar());
		addDetalle.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	    	  agregarDetalle();	    	  
	      }
	    });
	
		    
	    delDetalle = new Button(constants.eliminar(), IconHelper.createPath("images/icons/delete.gif"));
	    delDetalle.setEnabled(false);
	    delDetalle.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				BeanModel be =grid.getSelectionModel().getSelectedItem();
				grid.getStore().remove(be);
				
			}
		});
        toolBar.add(delDetalle);
	    
	    store = new ListStore<BeanModel>();
	    
	    RowNumberer r = new RowNumberer();
	    ArrayList<ColumnConfig> columns = new ArrayList<ColumnConfig>();
	    ColumnConfig column = new ColumnConfig();
	    columns.add(r);
	    columns.add(new ColumnConfig("descripcion", constants.gastoDescripcion(), 250));
	    
	    column = new ColumnConfig("monto", constants.gastoImporte(), 80);
        column.setAlignment(HorizontalAlignment.RIGHT);        
        columns.add(column); 
	    
		columns.add(new ColumnConfig("documento", constants.gastoDocumento(), 100));		
                
        columns.add(new ColumnConfig("numero", constants.gastoNumero(), 80));       
        
        
        column = new ColumnConfig("observaciones", constants.gastoObservaciones(), 250);        
        columns.add(column);
        
        ColumnModel cm = new ColumnModel(columns);       
        
        grid = new Grid<BeanModel>(store, cm);
        grid.addPlugin(r);
        grid.setBorders(false);
        grid.getSelectionModel().addListener(Events.SelectionChange, new Listener<SelectionChangedEvent<BeanModel>>(){

			@Override
			public void handleEvent(SelectionChangedEvent<BeanModel> be) {				
				if(be.getSelectedItem() != null)
					delDetalle.setEnabled(true);
				else
					delDetalle.setEnabled(false);
			}
		});
        
        gridPanel = new ContentPanel();
		gridPanel.setHeaderVisible(false);
		gridPanel.setLayout(new FitLayout());
		gridPanel.setHeight(330);
		gridPanel.add(grid);
		gridPanel.setTopComponent(toolBar);
        
       
        gastoFieldSet.add(setLayout(descripcion, "95%", 120),	new ColumnData(.8));
        gastoFieldSet.add(setLayout(monto, "100%", 50),new ColumnData(.2));
        gastoFieldSet.add(setLayout(observacion, "100%", 120),new ColumnData(1));
        gastoFieldSet.add(setLayout(documento, "80%", 120),	new ColumnData(.6));
        gastoFieldSet.add(setLayout(numerodocumento, "95%", 50),new ColumnData(.3));
        gastoFieldSet.add(addDetalle,new ColumnData(.1));
        
        formpanel.add(gastoFieldSet);
        add(formpanel);
        add(gridPanel);

	}
	
	@Override
	  protected void createButtons() {
	    super.createButtons();
	    
	    if (constants == null) {
	    	constants = GWT.create(MalouConstants.class);
		}
	    
	    status = new Status();
	    status.setBusy(constants.guardando());
	    status.hide();
	    status.setAutoWidth(true);
	    getButtonBar().add(status);
	    
	    getButtonBar().add(new FillToolItem());
	    
	    cancelar = new Button(constants.cancelar(),
				IconHelper.createPath("images/icons/cancel.png"));
		cancelar.setSize(70, 25);
	    cancelar.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {	    	  
	    	  IngresoDialog.this.hide();
	      }

	    });

	    guardar = new Button(constants.guardar(),
				IconHelper.createPath("images/icons/save_all.png"));
		guardar.setSize(70, 25);
	    guardar.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	    	  if(validarPrincipal()){
	    		  status.show();
	    		  getButtonBar().disable();
	    		  
	    		  List<Ingreso> list = new ArrayList<Ingreso>(); 
	    		  Ingreso gs;
	    		  	    		  
	    		  for(BeanModel b:store.getModels()){
	    			  gs = new Ingreso();
	    			  gs.setDescripcion(b.get("descripcion").toString());
	    			  gs.setFecha(new Date());
	    			  gs.setMonto(Double.valueOf(b.get("monto").toString()));
	    			  if(b.get("observaciones") != null)
	    			  gs.setObservaciones(b.get("observaciones").toString());
	    			  if(b.get("numero") != null)
	    			  gs.setNumero(b.get("numero").toString());
	    			  gs.setTipodocumento_id(Integer.valueOf(b.get("tipodocumento_id").toString()));
	    			  
	    			  list.add(gs);	    			  
	    		  }	    		  
	    		  
	    		  Ingresos.gastoDialog = IngresoDialog.this;
	    		  Ingresos.save(list);
	    	  }	    	  
	      }
	    });
	    
	    addButton(guardar);
	    addButton(cancelar);	    
	    
	  }
	
	public boolean validarDetalle(){
		descripcion.setAllowBlank(false);
		monto.setAllowBlank(false);		
		
		boolean des = descripcion.isValid();
		boolean mon = monto.isValid();		
		
		descripcion.setAllowBlank(true);
		monto.setAllowBlank(true);
		
		return des && mon; 
	}
	
	public boolean validarPrincipal(){
		
		boolean det = true;
		if(store.getCount()==0){
			det = false;
			MessageBox.alert(constants.sistemaMarcocruzado(), constants.detalleRequerido(), null);
			descripcion.focus();
		}
		
		return det;
	}
	
	public void clearDetalle(){
		  		  
		descripcion.clear();
		monto.clear();
		numerodocumento.clear();		
		observacion.clear();
				
		  
	 }
	public void clearPrincipal(){
		
		store.removeAll();
		clearDetalle();
		
	 }
	
	public void agregarDetalle(){
		if(validarDetalle()){
	    	  
		  Ingreso gs = new Ingreso();
		  
		  gs.setDescripcion(descripcion.getValue());		  
		  gs.setMonto(Double.valueOf(monto.getValue().toString()));
		  gs.setNumero(numerodocumento.getValue());
		  gs.setObservaciones(observacion.getValue());
		  gs.setTipodocumento_id(Integer.parseInt(documento.getValue().get("id").toString()));
		  gs.setDocumento(documento.getValue().get("descripcion").toString());
		  
    	  BeanModelFactory beanModelFactory =  BeanModelLookup.get().getFactory(gs.getClass());
    	  store.add(beanModelFactory.createModel(gs));
    	  clearDetalle();
    	  descripcion.focus();
	    	  		    	  
  	  }
	}
	
	private LayoutContainer setLayout(Component comp, String porcentaje,Integer withlabel) {
		LayoutContainer layout = new LayoutContainer();
		FormLayout fl = new FormLayout(LabelAlign.LEFT);
		fl.setLabelWidth(withlabel);
		layout.setLayout(fl);
		layout.add(comp, new FormData(porcentaje));

		return layout;
}
}
